<template>
    <div class="registered">
      <Header to='/personal/login' title='用户注册' />

        <el-form label-position="left" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" class="login-dialog" prop="username">
                <el-input type="text" placeholder="请输入用户名" v-model="ruleForm.username" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="tel">
                <el-input type="text" placeholder="请输入手机号码" v-model.number="ruleForm.tel">
                  </el-input>
            </el-form-item>
            <el-form-item label="验证码"  prop="verification">
                <el-input class="auth_input" type="text" v-model="ruleForm.verification" placeholder="请输入验证码" />
                <el-button
                  type="text"
                  :disabled="!sendAuthCode"
                  class="auth_text auth_text_blue"
                  @click="getAuthCode"
                >{{ sendAuthCode ? '获取验证码' : `${auth_time}秒之后重新发送验证码` }}</el-button>

                <!-- <span v-show="sendAuthCode" class="auth_text auth_text_blue" @click="getAuthCode">获取验证码</span> -->
                <!-- <span v-show="!sendAuthCode" class="auth_text"> <span class="auth_text_blue">{{auth_time}} </span>
                      秒之后重新发送验证码</span> -->
            </el-form-item>
            <el-form-item label="密码" prop="pass">
                <el-input type="password" placeholder="请输入密码" v-model="ruleForm.pass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" placeholder="请确认密码" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <div class="confirm-btn-div">
              <router-link :to="href">
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              </router-link>
            </div>
        </el-form>
        <div class="feedback-error" v-if="this.appear">
            <span>{{message}}</span>
        </div>

    </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
import { garbageMixin } from '../../utils/mixin'
import { setLocalStorage } from '../../utils/localStorage'
import Header from '../common/Header'
export default {
  mixins: [garbageMixin],
  components: {
    Header
  },
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const telCheck = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('电话号码是必须的'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('电话号码必须是数字'))
      } else if (value.toString().length !== 11) {
        return callback(new Error('电话号码必须是11位数字'))
      } else {
        this.telJudge = true
        callback()
      }
    }
    const verificationCheck = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }

    return {
      href: '',
      sendAuthCode: true,
      auth_time: 0,
      verifyCode: '',
      telJudge: false,
      appear: false,
      message: '请输入电话号码',
      ruleForm: {
        username: '',
        tel: '',
        pass: '',
        checkPass: '',
        verification: '' // 手机验证码
      },
      rules: {
        verification: [
          { required: true, validator: verificationCheck, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        tel: [
          { required: true, validator: telCheck, trigger: 'blur' }
        ],
        pass: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    saveData  () {
      // console.log(this.rules, 'llllllllll')
      this.setUserName(this.ruleForm.username)
      this.setUserPassword(this.ruleForm.checkPass)
      this.setUserPhone(this.ruleForm.tel)
      setLocalStorage('userName', this.ruleForm.username)
      setLocalStorage('userPassword', this.ruleForm.checkPass)
      setLocalStorage('userPhone', this.ruleForm.tel)
    },
    getAuthCode: function () {
      if (!this.telJudge) {
        this.appear = true
        setTimeout(() => {
          this.appear = false
        }, 1000)
        return
      }
      let params = {}
      params.phone = this.ruleForm.tel
      console.log(qs.stringify(params), 'll')
      axios.get('/sms?' + qs.stringify(params)).then(res => {
        console.log(res.data)
        if (res.data.code === 10001) {
          this.message = '手机号只能由13、14、15、17、18开头'
          this.appear = true
          setTimeout(() => {
            this.appear = false
          }, 2000)
          return false
        }
        if (res.data.code === 1) {
          this.verifyCode = res.data.data.verifyCode
          this.$message({
            message: '验证码已发送，请稍后、、、',
            type: 'sucess',
            center: true
          })
        }
      }).catch((error) => {
        console.log(error)
      })
      this.sendAuthCode = false
      // 设置倒计时秒
      this.auth_time = 30
      var authTimeTimer = setInterval(() => {
        this.auth_time--
        if (this.auth_time <= 0) {
          this.sendAuthCode = true
          clearInterval(authTimeTimer)
        }
      }, 1000)
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.verifyCode === this.ruleForm.verification) {
          console.log(this.verifyCode, this.ruleForm.verification)
          this.saveData()
        } else {
          return false
        }
      })
      let prefix = '/user?'
      let data = {
        username: this.ruleForm.username,
        password: this.ruleForm.pass,
        checkPass: this.ruleForm.checkPass,
        phone: this.ruleForm.tel
      }
      if (data.username === '') {
        return false
      } else if (data.phone === '') {
        return false
      } else if (data.password === '') {
        return false
      } else if (data.password !== data.checkPass) {
        return false
      }
      console.log(data, JSON.stringify(data))
      axios.post(prefix + this.$qs.stringify(data))
        .then((response) => {
          console.log(response, 'rrr')
          if (response.data.code === 1) {
            this.$message({
              message: '注册成功',
              type: 'success'
            })
            this.$router.push('/personal/login')
          } else if (response.data.code === 20005) {
            this.message = '该用户名已存在'
            this.appear = true
            setTimeout(() => {
              this.appear = false
            }, 2000)
          } else if (response.data.code === 10001) {
            this.message = '密码的长度为6-18'
            this.appear = true
            setTimeout(() => {
              this.appear = false
            }, 2000)
          }
        })
    }
  },
  mounted () {
    // console.log(this.ruleForm.checkPass)
  }
}
</script>

<style lang="scss" scoped>
@import '../../assets/styles/global';
.registered {
  position: relative;

  .el-form {
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
    padding: 0 10px;
    .el-form-item {
      margin-top: 20px;
      width: 100%;
    }
    .confirm-btn-div {
      margin-top: 20px;

    }
  }
  .feedback-error {
    display: block;
    background: #000;
    color: white;
    opacity: 0.4;
    font-size: 14px;
    width: 260px;
    height: 64px;
    line-height: 64px;
    border-radius: 10px;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

  }
}
</style>
